package com.fauks.ee.mq.rabbit;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class RabbitConsumer {
    public static void main(String[] args) throws Exception {
        //创建并配置连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.50.231");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("Sun830615");

        //通过连接工厂获取连接
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //声明列队
        String queueName = "test001";
        channel.queueDeclare(queueName, true, false, false, null);

        //创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        //设置channel
        channel.basicConsume(queueName, queueingConsumer);

        //循环获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            byte[] body = delivery.getBody();
            System.out.println("消费者获取数据：" + new String(body));
        }
    }
}
